package com.hqx.container;

import java.util.Arrays;
import java.util.Calendar;

public class DynamicArray<E> {
    private static final int DEFAULT_CAPACITY = 10;
    private int size;
    private Object[] elementData;

    public DynamicArray() {
        this.elementData = new Object[DEFAULT_CAPACITY];
    }

    /**
     * 数组扩容，先判断当前数组容量是否满足使用，不满足则扩大2倍，扩大后再判断是否满足最低使用，不满足则将数组扩大至最低是用容量
     * @param minCapacity
     */
    private void ensureCapacity(int minCapacity) {
        int oldCapacity = elementData.length;
        if (oldCapacity >= minCapacity) {
            return;
        }
        int newCapacity = oldCapacity * 2;
        if(newCapacity < minCapacity) {
            newCapacity = minCapacity;
        }
        elementData = Arrays.copyOf(elementData,newCapacity);
    }

    public void add(E e) {
        ensureCapacity(size + 1);
        elementData[size++] = e;
    }
    public void addAll(DynamicArray<? extends E> c) {
        for(int i=0; i<c.size; i++){
            add(c.get(i));
        }
    }

    public static int  indexOf(DynamicArray<?> arr,Object element) {
        for (int i = 0;i < arr.size;i++) {
            if(arr.get(i).equals(element)) {
                return i;
            }
        }
        return -1;
    }

//    public static void swap(DynamicArray<?> arr, int i, int j){
//        Object tmp = arr.get(i);
//        arr.set(i, arr.get(j));
//        arr.set(j, tmp);
//    }

    private static <T> void swapInternal(DynamicArray<T> arr, int i, int j){
        T tmp = arr.get(i);
        arr.set(i, arr.get(j));
        arr.set(j, tmp);
    }

//    public static <D,S extends D> void copy(DynamicArray<D> dest,
//                                            DynamicArray<S> src){
//        for(int i=0; i<src.size(); i++){
//            dest.add(src.get(i));
//        }
//    }


    public static <D> void copy(DynamicArray<D> dest,DynamicArray<? extends D> src) {
        for (int i = 0;i < src.size;i++) {
            dest.add(src.get(i));
        }
    }

    public void copyTo(DynamicArray<? super E> dest){
        for(int i=0; i<size; i++){
            dest.add(get(i));
        }
    }

    public E get(int index) {
        return (E) elementData[index];
    }
    public int size() {
        return size;
    }
    public E set(int index,E element) {
        E oldValue = get(index);
        elementData[index] = element;
        return oldValue;
    }
}
